<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * App\Models\Goods
 *
 * @property int $goods_id
 * @property string $goods_name 商品名称
 * @property int $cat_id goods_cat表的外键 分类id
 * @property float|null $price 商品的原价
 * @property float|null $discount_price 商品的现价或者打折价
 * @property float $sales_num 商品销量
 * @property float $stock 库存量
 * @property string|null $image 商品主图
 * @property string|null $ship_address 商品发货地
 * @property int $marketable 上下架状态 0-下架 1-上架
 * @property string|null $detail_content 商品详情介绍 富文本编辑内容
 * @property int $disabled 删除状态 0-未删除 1-已删除
 * @property int $sort 商品排序的序号
 * @property string|null $bn 商品编码
 * @property \Carbon\Carbon|null $created_at
 * @property \Carbon\Carbon|null $updated_at
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Comment[] $comment
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goods whereBn($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goods whereCatId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goods whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goods whereDetailContent($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goods whereDisabled($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goods whereDiscountPrice($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goods whereGoodsId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goods whereGoodsName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goods whereImage($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goods whereMarketable($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goods wherePrice($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goods whereSalesNum($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goods whereShipAddress($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goods whereSort($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goods whereStock($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goods whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class Goods extends Model
{
    protected $table = 'goods';
    protected $primaryKey = 'goods_id';
    protected $guarded = [];

    public $error;
    public function comment()
    {
      return $this->hasMany('App\Models\Comment','goods_id');
    }

    /**
     * spu列表的获取
     */
    public function data()
    {
        return $this->newQuery()
            -> select($this->table.'.*','goods_cate.cate_name',DB::raw('IFNULL(discount_price,price) discount_price'))
            -> leftJoin('goods_cate', $this->table.'.cat_id', '=', 'goods_cate.id')
            -> orderBy('sort','asc')
            -> get()
            -> toArray();
    }

    /**
     * spu的新增
     *
     * @param $params
     * @return bool
     * @throws Exception
     */
    public function add($params)
    {

        DB::beginTransaction();
        $time = time();
        try {
            //商品数据
            $goods_id = $this->insertGetId([
                'goods_name'     => $params['Goods']['name'],
                'detail_content' => $params['Goods']['detail_content'],
                'cat_id'         => $params['Goods']['cat_id']
            ]);

            if (!$goods_id) {
               throw new \Exception('goods表添加失败');
            }

            //sku的添加
            $this -> add_goods_props($goods_id, $params);

            //商品图片的保存
            $this -> save_goods_iamge($goods_id,$params);
            DB::commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            DB::rollBack();
            return false;
        }
    }

    /**商品的编辑
     * @param $params
     * @return bool
     */
    public function edit($spu_id,$params)
    {
        DB::beginTransaction();
        $time = time();
        try {
            //商品基本信息
            $this->newQuery()->where('goods_id',$spu_id)->update($params['Goods']);

            //货品数据
            if(!$res = self::edit_goods_props($spu_id,$params)){
                throw new \Exception(self::$error);
            }


            //商品-图片
            if (isset($params['Image']['url']) && $params['Image']['url']) {
                $spu_model = Goods::findOne($goods_id);
                $del_image_id_arr = Parton_saint::del_arr(array_values($params['Image']['key']),array_column(GoodsBanner::find()->asArray()->where(['goods_id'=>$goods_id,'disabled'=>'false'])->all(),'id'));
                if(!empty($del_image_id_arr)){
                    GoodsBanner::updateAll(['disabled'=>1,'is_default'=>0],['id'=>$del_image_id_arr]);
                }
                foreach ($params['Image']['url'] as $image_k=>$image_v)
                {
                    //没有加入数据库的图片 则需要插入数据库
                    if ($params['Image']['key'][$image_k] == 0) {
                        //插入goodsBanner表
                        $command -> createCommand() -> insert(
                            GoodsBanner::tableName(),
                            [
                                'goods_id'       => $goods_id,
                                'image_url'      => $image_v,
                            ]
                        )->execute();
                        $banner_id = $command -> getLastInsertID();
                    }else{
                        $banner_id = $params['Image']['key'][$image_k];
                    }
                    if($params['Image']['default'][$image_k] == 1){
                        $banner_model = GoodsBanner::findOne(['goods_id'=>$goods_id,'is_default'=>1]);
                        if(!empty($banner_model)){
                            $banner_model -> is_default = 0;
                            $banner_model -> save();
                        }
                        $banner_model = GoodsBanner::findOne($banner_id);
                        $banner_model -> is_default = 1;
                        $banner_model -> save();
                        $spu_model -> image_url = $image_v;
                        $spu_model -> save();
                    }
                }
            }else{
                //删除数据库剩下的所有图片
                $del_image_id_arr = array_column(GoodsBanner::find()->asArray()->where(['goods_id'=>$spu_id,'disabled'=>'false'])->all(),'id');
                if(!empty($del_image_id_arr)){
                    GoodsBanner::updateAll(['disabled'=>1,'is_default'=>0],['id'=>$del_image_id_arr]);
                }
                //将该spu的img_url清空
                $spu_model = Goods::findOne($spu_id);
                $spu_model -> image_url = '';
                $spu_model -> save();
            }

            DB::commit();
            return true;
        } catch (\Exception $e) {
            var_dump($e->getMessage());exit;
            DB::rollBack();
            return false;
        }
    }

    /**获取用于前端显示的分类列表，最多两级分类
     * @param $cate
     * @param string $html
     * @param int $pid
     * @param int $level
     * @return array
     */
    public function getHtmlCate($cate,$html="-",$pid=0, $level=0){
        //定义空数组
        $arr = array();
        //遍历数组
        foreach($cate as $v){
            if($v['pid'] == $pid){
//                dd($html,$level);
                $v['html'] = str_repeat($html, $level);
                $v['level'] = $level;
                $arr[] = $v;
                $arr = array_merge($arr,$this->getHtmlCate($cate,$html,$v['id'],$level+1));
            }
        }

        return $arr;
    }

    /**纯添加sku的属性，属性值关系
     * @param $spu_id   商品spu_id
     * @param $post     提交过来的post数据
     */
    private function add_goods_props($spu_id,$post)
    {
        if(empty($post['specs'])){
            return true;
        }
        $postSkuInfo = $post['sku'];
        $sku_store = 0; //库存
        $discount_money = null; //折扣价
        $price = null; //市场价初始值

        $spu_model = self::find($spu_id);

        //遍历每个sku 添加 sku
        foreach($post['specs'] as $row => $sku){
            if($postSkuInfo[$row]['discount_money']){
                //有一件sku有折扣 就将该spu标记为打折的商品
                $is_discount = 1;
                $discount_money = $postSkuInfo[$row]['discount_money']; //去最后一个折扣价为该spu的折扣价
            }
            if(!$price){
                $price = $postSkuInfo[$row]['price'];
            }
            if($price > $postSkuInfo[$row]['price']){
                //计算出最低价格
                $price = $postSkuInfo[$row]['price'];
            }
            //添加商品的sku
            $sku_data = [
                'name' =>$spu_model->goods_name,
                'title'=>$spu_model->goods_name,
                'bn'   =>$postSkuInfo[$row]['bn'],
                'discount_price'=>empty($postSkuInfo[$row]['discount_money'])?0:$postSkuInfo[$row]['discount_money'],
                'goods_id'=>$spu_id,
                'price'=>$postSkuInfo[$row]['price'],
                'stock'=>$postSkuInfo[$row]['store'],
                //'is_default'=>$row==0?'true':'false',
            ];
            $sku_store += $postSkuInfo[$row]['store']; //统计库存

            //如果该
            if($sku_model = Product::create($sku_data)){
                //添加sku的属性，属性值

                $sku_id = $sku_model -> prodcut_id;
                foreach($sku as $prop_key => $prop_arr){
                    $sku_prop_data = [
                        'sku_id'        => $sku_id,
                        'spu_id'        => $spu_id,
                        'props_id'      => $prop_key,
                        'props_val_id'=> $prop_arr['attr_vid'],
                    ];
                    $res = sku_props_vals::create($sku_prop_data);
                    if(!$res){
                        throw new \Exception('商品属性表插入失败'.serialize($sku_prop_data));
                    }
                }
            }else{
                throw new \Exception('商品sku添加失败---'.serialize($sku_data));
            }

        }
        $spu_model -> price = $price;
//        $spu_model -> is_discount = $is_discount;
        $spu_model -> discount_price = $discount_money;
        $spu_model -> stock = $sku_store;
        if(!$spu_model->save()){
            throw new \Exception('商品spu更新失败---'.serialize($spu_model));
        }
    }

    /**纯编辑sku的属性，属性值关系
     * @param $spu_id
     * @param $post
     */
    private function edit_goods_props($spu_id,$post){
        $spu_model = $this -> find($spu_id);
        $postSkuInfo = $post['sku'];
        $sku_store = 0; //库存
        $discount_money = null;
        $is_discount = 0;
        $price = null; //市场价初始值
        //如果传过来的是未被破坏的table 只需要修改sku的库存 折扣价 和商品编码等属性
        if(isset($post['sku']) && isset($post['sku'][0]['sku_id'])){
            if(isset($post['specs'])){
                foreach($post['specs'] as $row => $sku){
                    if($postSkuInfo[$row]['discount_money']){
                        //有一件sku有折扣 就将该spu标记为打折的商品
                        $is_discount = 1;
                        $discount_money = $postSkuInfo[$row]['discount_money']; //去最后一个折扣价为该spu的折扣价
                    }
                    if(!$price){
                        $price = $postSkuInfo[$row]['price'];
                    }
                    if($price > $postSkuInfo[$row]['price']){
                        //计算出最低价格
                        $price = $postSkuInfo[$row]['price'];
                    }

                    //添加商品的sku
                    $sku_data  = [
                        'name' => $spu_model->name,
                        'title'=> $spu_model->name,
                        'bn'   => $postSkuInfo[$row]['bn'],
                        'discount_money'=>empty($postSkuInfo[$row]['discount_money'])?0:$postSkuInfo[$row]['discount_money'],
                        'goods_id'=>$spu_id,
                        'last_modify'=>time(),
                        'price'=>$postSkuInfo[$row]['price'],
                        'store'=>$postSkuInfo[$row]['store']
                    ];
                    $sku_store += $postSkuInfo[$row]['store']; //统计库存
                    if(!Product::create($sku_data)){
                        throw new \Exception('产品表更细是吧');
                    }
                }
            }else{
                if($postSkuInfo[0]['discount_money']){
                    //有一件sku有折扣 就将该spu标记为打折的商品
                    $is_discount = 1;
                    $discount_money = $postSkuInfo[0]['discount_money']; //去最后一个折扣价为该spu的折扣价
                }
                if(!$price){
                    $price = $postSkuInfo[0]['price'];
                }
                if($price > $postSkuInfo[0]['price']){
                    //计算出最低价格
                    $price = $postSkuInfo[0]['price'];
                }

                //没有任何属性的商品
                $sku_model = GoodsProducts::findOne($post['sku'][0]['sku_id']);
                $sku_data  = [
                    'name'=>$spu_model->name,
                    'title'=>$spu_model->name,
                    'bn'=>$postSkuInfo[0]['bn'],
                    'discount_money'=>empty($postSkuInfo[0]['discount_money'])?0:$postSkuInfo[0]['discount_money'],
                    'goods_id'=>$spu_id,
                    'last_modify'=>time(),
                    'price'=>$postSkuInfo[0]['price'],
                    'store'=>$postSkuInfo[0]['store']
                ];
                $sku_model -> load($sku_data,'') && $sku_model -> save();
                $sku_store = $postSkuInfo[0]['store'];
            }
            $spu_model -> price = $price;
            $spu_model -> is_discount = $is_discount;
            $spu_model -> discount_money = $discount_money;
            $spu_model -> store = $sku_store;
            if(!$spu_model->save()){
                self::$error = array_values($spu_model->getFirstErrors())[0];
                return false;
            }
            return true;
        }else{
            //是已经被破坏的sku_id  需要删除原来的sku_id
            //删除原来的sku_id
            $del_sku_id = isset($post['sku_id'])?$post['sku_id']:[];
            if(!empty($del_sku_id)){
                //将相关的sku_id删除
                GoodsProducts::updateAll(['disabled'=>'true'],['product_id'=>$del_sku_id]);
                GoodsPropsRelation::updateAll(['disabled'=>'true'],['products_id'=>$del_sku_id]);
            }
            //遍历每个sku 添加 sku
            foreach($post['specs'] as $row => $sku){
                if($postSkuInfo[$row]['discount_money']){
                    //有一件sku有折扣 就将该spu标记为打折的商品
                    $is_discount = 1;
                    $discount_money = $postSkuInfo[$row]['discount_money']; //去最后一个折扣价为该spu的折扣价
                }
                if(!$price){
                    $price = $postSkuInfo[$row]['price'];
                }
                if($price > $postSkuInfo[$row]['price']){
                    //计算出最低价格
                    $price = $postSkuInfo[$row]['price'];
                }
                //添加商品的sku
                $sku_model = new GoodsProducts();
                $sku_data = [
                    'name'=>$spu_model->name,
                    'title'=>$spu_model->name,
                    'bn'=>$postSkuInfo[$row]['bn'],
                    'discount_money'=>empty($postSkuInfo[$row]['discount_money'])?0:$postSkuInfo[$row]['discount_money'],'goods_id'=>$spu_id,
                    'last_modify'=>time(),
                    'price'=>$postSkuInfo[$row]['price'],
                    'store'=>$postSkuInfo[$row]['store'],
                    'is_default'=>$row==0?'true':'false',
                ];
                $sku_store+=$postSkuInfo[$row]['store'];//累加库存

                if($sku_model -> load($sku_data,'') && $sku_model -> save()){
                    //添加sku的属性，属性值
                    $sku_id = $sku_model -> product_id;
                    foreach($sku as $prop_key => $prop_arr){
                        $sku_prop_realtion_model = new GoodsPropsRelation();
                        $sku_prop_data = [
                            'products_id'=>$sku_id,
                            'goods_id'=>$spu_id,
                            'props_id'=>$prop_key,
                            'props_value_id'=>$prop_arr['attr_vid'],
                            'last_modify'=>time()
                        ];
                        $res = $sku_prop_realtion_model -> load($sku_prop_data,'') && $sku_prop_realtion_model -> save();
                        if(!$res){
                            self::$error=array_values($sku_prop_realtion_model->getFirstErrors())[0].__LINE__;
                            return false;
                        }
                    }
                }else{
                    self::$error= array_values($sku_model->getFirstErrors())[0].__LINE__;
                    return false;
                }

            }
            $spu_model -> price = $price;
            $spu_model -> is_discount = $is_discount;
            $spu_model -> discount_money = $discount_money;
            $spu_model -> store = $sku_store;
            if(!$spu_model->save()){
                self::$error = array_values($spu_model->getFirstErrors())[0];
                return false;
            }
            return true;
        }
    }


    /**商品图片的添加或者更新
     * @param $spu_id
     * @param $post
     */
    private function save_goods_iamge($spu_id,$params)
    {

        //添加商品-图片
        if (isset($params['Image']['url']) && $params['Image']['url']) {
            $spu_model = $this -> find($spu_id);
            foreach ($params['Image']['url'] as $image_k => $image_v) {
                //没有加入数据库的图片 则需要插入数据库
                if ($params['Image']['key'][$image_k] == 0) {
                    //插入GoodsImage表

                    $goodsImageModel = GoodsImage::create([
                        'goods_id' => $spu_id,
                        'image' => $image_v,
                    ]);
                    $banner_id = $goodsImageModel -> goods_image_id;
                }else{
                    $banner_id = $params['Image']['key'][$image_k];
                }

                if ($params['Image']['default'][$image_k] == 1) {

                    //将原有的默认图片改为不是默认的
                    $banner_model = GoodsImage::query()->where([['goods_id',$spu_id], ['is_default',1]])->first();
                    if (!empty($banner_model)) {
                        $banner_model->is_default = 0;
                        $banner_model->save();
                    }

                    //将现在的图片改为默认图片
                    $banner_model = GoodsImage::find($banner_id);
                    $banner_model -> is_default = 1;
                    $banner_model -> save();

                    //将默认图片保存进goods表
                    $spu_model -> image = $image_v;
                    $spu_model -> save();
                }
            }
        }
    }


    /**
     * 商品分类列表的获取
     */
    private function goods_cat_list()
    {

    }





}
